import type { AxiosResponse } from "axios";
import axios from "./index";
import {
  ORDER_STATUS,
  type NewOrder,
  type Order,
  type PaginatedOrdersResponse,
  type Result,
} from "./types";

// 获取分页的订单列表
export async function fetchOrders(
  page: number,
  limit: number
): Promise<Result<PaginatedOrdersResponse>> {
  const response: AxiosResponse<Result<PaginatedOrdersResponse>> =
    await axios.get(`/orders/getAll?page=${page}&limit=${limit}`);
  return response.data;
}

// 根据用户ID获取其所有订单
export async function fetchOrdersByUserId(
  userId: number,
  status: keyof typeof ORDER_STATUS | "all"
): Promise<Result<Order[]>> {
  const response: AxiosResponse<Result<Order[]>> = await axios.get(
    `/orders/user/${userId}`,
    {
      params: {
        status: status === "all" ? undefined : ORDER_STATUS[status],
      },
    }
  );
  return response.data;
}

// 创建新订单
export async function createOrder(orderData: NewOrder): Promise<Result> {
  const response: AxiosResponse<Result> = await axios.post(
    "/orders/add",
    orderData
  );
  return response.data;
}

// 删除订单
export async function deleteOrder(orderId: number): Promise<void> {
  await axios.delete(`/orders/${orderId}`);
}

// 发货操作
export async function shipOrder(
  orderId: number,
  expressCode: string
): Promise<{ success: boolean; message: string }> {
  try {
    const response: AxiosResponse<{ success: boolean; message: string }> =
      await axios.put(`/orders/ship/${orderId}`, { expressCode });
    return response.data;
  } catch (error: any) {
    // 错误处理可以根据实际情况调整
    throw new Error(error.response?.data.message || "发货操作失败");
  }
}

// 收货操作
export async function receiveOrder(
  orderId: number
): Promise<{ success: boolean; message: string }> {
  try {
    const response: AxiosResponse<{ success: boolean; message: string }> =
      await axios.put(`/orders/receive/${orderId}`);
    return response.data;
  } catch (error: any) {
    // 错误处理可以根据实际情况调整
    throw new Error(error.response?.data.message || "收货操作失败");
  }
}

export async function salesByDay(): Promise<any> {
  let { data } = await axios.get(`/orders/salesByDay`);
  return data.data;
}

export async function totalPrice(): Promise<number> {
  let { data } = await axios.get(`/orders/totalPrice`);
  return data.data;
}
export async function totalOrders(): Promise<number> {
  let { data } = await axios.get(`/orders/totalOrders`);
  return data.data;
}
